package com.zenithmind.chat.controller;

import com.zenithmind.chat.pojo.dto.ChatPrivateMessageDTO;
import com.zenithmind.chat.pojo.vo.ChatPrivateMessageVO;
import com.zenithmind.chat.service.ChatPrivateMessageService;
import com.zenithmind.common.context.UserContext;
import com.zenithmind.common.result.PageResult;
import com.zenithmind.common.result.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import java.util.List;

/**
 * 私聊消息控制器 - 遵循单一职责原则
 * 只负责私聊消息的HTTP接口处理
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@RestController
@RequestMapping("/api/chat/private-messages")
@RequiredArgsConstructor
@Validated
@Tag(name = "私聊消息管理", description = "私聊消息相关接口")
public class ChatPrivateMessageController {

    private final ChatPrivateMessageService chatPrivateMessageService;

    @PostMapping
    @Operation(summary = "发送私聊消息", description = "发送私聊消息")
    public Result<String> sendMessage(@Valid @RequestBody ChatPrivateMessageDTO dto) {
        String userId = UserContext.getUserId();
        String messageId = chatPrivateMessageService.sendMessage(dto, userId);
        return Result.success(messageId);
    }

    @GetMapping("/session/{sessionId}")
    @Operation(summary = "查询会话消息", description = "分页查询指定会话的消息列表")
    public Result<PageResult<ChatPrivateMessageVO>> getSessionMessages(
            @Parameter(description = "会话ID") @PathVariable @NotBlank String sessionId,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        String userId = UserContext.getUserId();
        PageResult<ChatPrivateMessageVO> result = chatPrivateMessageService.getMessagePage(sessionId, userId, pageNum, pageSize);
        return Result.success(result);
    }

    @GetMapping("/{messageId}")
    @Operation(summary = "查询消息详情", description = "根据消息ID查询消息详细信息")
    public Result<ChatPrivateMessageVO> getMessageById(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        ChatPrivateMessageVO message = chatPrivateMessageService.getMessageById(messageId, userId);
        return Result.success(message);
    }

    @PutMapping("/{messageId}")
    @Operation(summary = "编辑消息", description = "编辑已发送的私聊消息")
    public Result<Boolean> editMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId,
            @Parameter(description = "新内容") @RequestParam @NotBlank String content) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.editMessage(messageId, content, userId);
        return Result.success(result);
    }

    @DeleteMapping("/{messageId}")
    @Operation(summary = "撤回消息", description = "撤回已发送的私聊消息")
    public Result<Boolean> recallMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.recallMessage(messageId, userId);
        return Result.success(result);
    }

    @PostMapping("/{messageId}/forward")
    @Operation(summary = "转发消息", description = "转发私聊消息到其他会话")
    public Result<Boolean> forwardMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId,
            @RequestBody @NotEmpty List<String> targetSessionIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.forwardMessage(messageId, targetSessionIds, userId);
        return Result.success(result);
    }

    @PostMapping("/{messageId}/reply")
    @Operation(summary = "回复消息", description = "回复指定的私聊消息")
    public Result<String> replyMessage(
            @Parameter(description = "消息ID") @PathVariable @NotBlank String messageId,
            @Valid @RequestBody ChatPrivateMessageDTO dto) {
        String userId = UserContext.getUserId();
        String replyMessageId = chatPrivateMessageService.replyMessage(messageId, dto, userId);
        return Result.success(replyMessageId);
    }

    @PostMapping("/mark-read")
    @Operation(summary = "标记消息已读", description = "标记私聊消息为已读状态")
    public Result<Boolean> markAsRead(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "消息ID") @RequestParam(required = false) String messageId) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.markAsRead(sessionId, messageId, userId);
        return Result.success(result);
    }

    @GetMapping("/unread-count")
    @Operation(summary = "查询未读消息数", description = "查询当前用户的未读私聊消息总数")
    public Result<Integer> getUnreadCount(
            @Parameter(description = "会话ID") @RequestParam(required = false) String sessionId) {
        String userId = UserContext.getUserId();
        Integer unreadCount = chatPrivateMessageService.getUnreadCount(userId, sessionId);
        return Result.success(unreadCount);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索消息", description = "在私聊会话中搜索消息")
    public Result<PageResult<ChatPrivateMessageVO>> searchMessages(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "关键词") @RequestParam @NotBlank String keyword,
            @Parameter(description = "消息类型") @RequestParam(required = false) Integer messageType,
            @Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer pageNum,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") Integer pageSize) {
        String userId = UserContext.getUserId();
        PageResult<ChatPrivateMessageVO> result = chatPrivateMessageService.searchMessages(sessionId, keyword, messageType, pageNum, pageSize, userId);
        return Result.success(result);
    }

    @PostMapping("/batch-delete")
    @Operation(summary = "批量删除消息", description = "批量删除指定的私聊消息")
    public Result<Boolean> batchDeleteMessages(@RequestBody @NotEmpty List<String> messageIds) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.batchDeleteMessages(messageIds, userId);
        return Result.success(result);
    }

    @GetMapping("/statistics")
    @Operation(summary = "消息统计", description = "获取私聊消息统计信息")
    public Result<Object> getMessageStatistics(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "统计类型") @RequestParam @NotBlank String statisticsType) {
        String userId = UserContext.getUserId();
        Object statistics = chatPrivateMessageService.getMessageStatistics(sessionId, statisticsType, userId);
        return Result.success(statistics);
    }

    @GetMapping("/export")
    @Operation(summary = "导出消息", description = "导出私聊消息记录")
    public Result<String> exportMessages(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
            @Parameter(description = "导出格式") @RequestParam(defaultValue = "excel") String format) {
        String userId = UserContext.getUserId();
        String exportUrl = chatPrivateMessageService.exportMessages(sessionId, startTime, endTime, format, userId);
        return Result.success(exportUrl);
    }

    @PostMapping("/clear-history")
    @Operation(summary = "清空聊天记录", description = "清空指定会话的聊天记录")
    public Result<Boolean> clearChatHistory(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.clearChatHistory(sessionId, userId);
        return Result.success(result);
    }

    @GetMapping("/recent")
    @Operation(summary = "查询最近消息", description = "查询当前用户的最近私聊消息")
    public Result<List<ChatPrivateMessageVO>> getRecentMessages(
            @Parameter(description = "数量限制") @RequestParam(defaultValue = "10") Integer limit) {
        String userId = UserContext.getUserId();
        List<ChatPrivateMessageVO> messages = chatPrivateMessageService.getRecentMessages(userId, limit);
        return Result.success(messages);
    }

    @PostMapping("/auto-reply")
    @Operation(summary = "设置自动回复", description = "设置私聊自动回复消息")
    public Result<Boolean> setAutoReply(
            @Parameter(description = "是否启用") @RequestParam Boolean enabled,
            @Parameter(description = "自动回复内容") @RequestParam(required = false) String content) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.setAutoReply(userId, enabled, content);
        return Result.success(result);
    }

    @GetMapping("/draft")
    @Operation(summary = "获取草稿", description = "获取指定会话的草稿消息")
    public Result<String> getDraft(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId) {
        String userId = UserContext.getUserId();
        String draft = chatPrivateMessageService.getDraft(sessionId, userId);
        return Result.success(draft);
    }

    @PostMapping("/draft")
    @Operation(summary = "保存草稿", description = "保存会话的草稿消息")
    public Result<Boolean> saveDraft(
            @Parameter(description = "会话ID") @RequestParam @NotBlank String sessionId,
            @Parameter(description = "草稿内容") @RequestParam String content) {
        String userId = UserContext.getUserId();
        Boolean result = chatPrivateMessageService.saveDraft(sessionId, content, userId);
        return Result.success(result);
    }
}
